"use client";

import {
  createContext,
  useState,
  useRef,
  useEffect,
  useCallback,
  ReactNode,
} from "react";
import {
  KeyInfo,
  MacroProfile,
  FilterDevice,
  KeyItem,
  LightInfo,
  KeyboardProfile,
  KeyColor,
} from "../types/types";
import { DeviceComm, connectDeviceHID } from "../devices/KeyboardDevice";
import { useTranslation } from "../i18n";
import _ from "lodash";

type MainProps = {
  softwareVersion: string;
  connectedKeyboard?: DeviceComm;
  connectKeyboard: Function;
  disconnectKeyboard: Function;

  demoMode: boolean; // 演示模式
  setDemoMode: Function;

  connectMode: string;
  deviceStatus: boolean; // 设备连接状态
  setDeviceStatus: Function;
  deviceOnline: boolean; // 设备是否在线
  setDeviceOnline: Function;
  deviceName: string; // 设备名称
  setDeviceName: Function;
  deviceId: string; // 设备ID
  setDeviceId: Function;
  deviceVersion: string; // 设备版本
  setDeviceVersion: Function;
  dongleVersion: string; // 接收器版本
  setDongleVersion: Function;
  currentTab: string; // 当前选中的标签
  setCurrentTab: Function;
  isRecordingMacro: boolean; // 是否正在录制宏
  setIsRecordingMacro: Function;

  profileIndex: number; // 当前选中的配置文件
  setProfileIndex: Function;
  profiles: KeyboardProfile[]; // 配置文件
  setProfiles: Function;
  activeProfile: Function;
  updateKeyboardKeys: Function;
  updateKeyboardKeyColor: Function;

  fnLayer: number;
  setFnLayer: Function;
  selectedKeyIndex: number;
  setSelectedKeyIndex: Function;
  multiSelectKeys: number[];
  setMultiSelectKeys: Function;
  keyInfos: KeyInfo[]; // 按键信息
  setKeyInfos: Function;
  keyColor: KeyColor[]; // 按键颜色
  setKeyColor: Function;
  kbMatrix: number[]; // 键盘矩阵
  setKbMatrix: Function;
  currentLightMode: number; // 当前灯光模式
  setCurrentLightMode: Function;
  currentColor: string;
  setCurrentColor: Function;
  lockWin: number;
  setLockWin: Function;
  lockAltF4: number;
  setLockAltF4: Function;
  lockAltTab: number;
  setLockAltTab: Function;

  localMacroName: string; // 本地宏名称
  macroProfiles: MacroProfile[]; // 宏配置文件
  setMacroProfiles: Function;
  selectMacroProfile: number; // 当前选中的宏配置文件
  setSelectMacroProfile: Function;

  setMacroData?: Function;
  editMode?: string;
  setEditMode?: Function;

  battery: number;
  chargeFlag: number;
  t: Function;

  // 灯光信息
  lightInfo: LightInfo[];
  setLightInfo: Function;
  // 恢复键盘出厂设置
  restoreKeyboardFactorySettings: Function;
};

export const MainContext = createContext({} as MainProps);

export function MainProvider({ children }: { children: ReactNode }) {
  // 软件版本
  const [softwareVersion, setSoftwareVersion] = useState("1.0.1");
  const [connectedKeyboard, setConnectedKeyboard] = useState<DeviceComm>();

  // 演示模式
  const [demoMode, setDemoMode] = useState(false);
  // 设备连接状态
  const [deviceStatus, setDeviceStatus] = useState(false);
  // 设备是否在线
  const [deviceOnline, setDeviceOnline] = useState(false);

  const [connectMode, setConnectMode] = useState("USB");
  // 设备名称
  const [deviceName, setDeviceName] = useState("");
  // 设备ID
  const [deviceId, setDeviceId] = useState("");
  // 设备版本
  const [deviceVersion, setDeviceVersion] = useState("1.0.1");
  // 接收器版本
  const [dongleVersion, setDongleVersion] = useState("1.0.1");

  const [currentTab, setCurrentTab] = useState("kb-keyremap");
  // 宏录制状态
  const [isRecordingMacro, setIsRecordingMacro] = useState(false);

  // 本地键盘信息文件
  const [localKeyboardInfoFile, setLocalKeyboardInfoFile] = useState(
    "@/src/config/keyboard_info_3.json"
  );
  // 本地配置文件名称
  const [localProfileName, setLocalProfileName] = useState(
    "yjxkeyboard_profiles_k81_v3"
  );

  // 当前选中的配置文件
  const [profileIndex, setProfileIndex] = useState(0);
  const [profiles, setProfiles] = useState<KeyboardProfile[]>([]);

  // Fn层信息
  const [fnLayer, setFnLayer] = useState(0);
  // 当前选中的按键索引
  const [selectedKeyIndex, setSelectedKeyIndex] = useState(-1);
  // 多选按键
  const [multiSelectKeys, setMultiSelectKeys] = useState<number[]>([]);
  // 当前颜色
  const [currentColor, setCurrentColor] = useState<string>("#FF0000");

  // 键盘按键信息
  const [keyInfos, setKeyInfos] = useState<KeyInfo[]>([]);
  // 键盘矩阵
  const [kbMatrix, setKbMatrix] = useState<number[]>([]);

  // 当前灯光模式
  const [currentLightMode, setCurrentLightMode] = useState(0);
  // 灯光信息
  const [lightInfo, setLightInfo] = useState<LightInfo[]>([]);
  // 按键颜色
  const [keyColor, setKeyColor] = useState<KeyColor[]>([]);

  const [lockWin, setLockWin] = useState(0);
  const [lockAltF4, setLockAltF4] = useState(0);
  const [lockAltTab, setLockAltTab] = useState(0);

  // 本地宏名称
  const [localMacroName, setLocalMacroName] = useState("keyboard_macro_yjx_v3");
  const [macroProfiles, setMacroProfiles] = useState<MacroProfile[]>([]);
  const [selectMacroProfile, setSelectMacroProfile] = useState(0);

  const [battery, setBattery] = useState(100);
  const [chargeFlag, setChargeFlag] = useState(0);

  const { t } = useTranslation("common");
  const initDemo = async () => {
    setDeviceStatus(true);
    setDeviceOnline(true);
    setBattery(100);
    setChargeFlag(0);
    await loadKeyboardDefaultConfig();
    return true;
  };


  // 加载键盘默认配置
  const loadKeyboardDefaultConfig = async () => {
    try {
      let defaultConfig: any = await import("@/src/data/layout/k81.json");

      // 遍历键盘按键布局，生成按键信息
      const standardLayerKeys = defaultConfig.default.layouts.keys.map(
        (key: KeyItem) => ({
          index: key.index,
          layer: 0,
          keyValue: key.code,
          keyName: key.name,
          lang: "",
          type: 0x00,
          code1: 0x00,
          code2: 0x00,
          code3: 0x00,
          fnName1: "",
          fnType: 0x00,
          fnCode1: 0x00,
          fnCode2: 0x00,
          fnCode3: 0x00,
        })
      );
      setKeyInfos(standardLayerKeys);
      console.log("standardLayerKeys", standardLayerKeys);
      // 初始化按键颜色
      const keyColor: KeyColor[] = defaultConfig.default.layouts.keys.map(
        (key: KeyItem) => ({
          index: key.index,
          keyValue: key.code,
          keyName: key.name,
          keyColor: "#000000",
        })
      );
      setKeyColor(keyColor);
      // 初始化22个灯光模式
      const lightInfo: LightInfo[] = [];
      for (let i = 0; i < 22; i++) {
        lightInfo.push({
          name: `Light${i}`,
          lang: "",
          status: 1,
          type: 0,
          mode: i,
          brightness: 200, // 默认亮度200 (范围0-255)
          speed: 3, // 默认速度3 (范围0-3)
          direction: 0,
          colorful: 0,
          colorValue: 0x0091ff, // 默认蓝色
          colorIndex: 0,
          lockWin: 0,
          lockAltF4: 0,
          lockAltTab: 0,
        });
      }
      setLightInfo(lightInfo);

      // 初始化配置
      let keyboardProfile: KeyboardProfile[] = [
        {
          name: "Profile1",
          active: true,
          kbKeys: standardLayerKeys,
          lightInfo: lightInfo,
          keyColor: keyColor,
        },
        {
          name: "Profile2",
          active: false,
          kbKeys: standardLayerKeys,
          lightInfo: lightInfo,
          keyColor: keyColor,
        },
        {
          name: "Profile3",
          active: false,
          kbKeys: standardLayerKeys,
          lightInfo: lightInfo,
          keyColor: keyColor,
        },
        {
          name: "Profile4",
          active: false,
          kbKeys: standardLayerKeys,
          lightInfo: lightInfo,
          keyColor: keyColor,
        },
        {
          name: "Profile5",
          active: false,
          kbKeys: standardLayerKeys,
          lightInfo: lightInfo,
          keyColor: keyColor,
        },
      ];
      initKeyboardProfiles(keyboardProfile);
    } catch (error) {
      console.error("加载默认配置失败:", error);
    }
  };

  // 连接设备
  const connectKeyboard = async (filter: FilterDevice[] | undefined) => {
    // 这里判断是否是演示模式
    // if (1) {
    //   return initDemo();
    // }
    // 为了安全起见，先断开之前可能存在的连接
    if (connectedKeyboard) {
      // 清空所有监听器
      console.log("清空现有设备的监听器");
      connectedKeyboard.onListeners = [];
    }
    // 连接设备
    const newDevice = await connectDeviceHID(filter);
    if (newDevice === undefined) {
      console.log("connectedKeyboard undefined, not find device!");
      setDeviceStatus(false);
      setDeviceOnline(false);
      return false;
    }

    setConnectedKeyboard(newDevice);
    console.log("connectedKeyboard", newDevice);
    // 设置设备名称
    setDeviceName(newDevice.productName);
    // 获取连接模式

    let connected_mode = await newDevice.getConnectMode();
    console.log("connected_mode", connected_mode);
    setConnectMode(connected_mode);

    await loadKeyboardDefaultConfig();
    if (connected_mode == "USB" || connected_mode == "BLE") {
      // 设置设备连接状态
      setDeviceStatus(true);
      setDeviceOnline(true);
      // 加载键盘数据
      await loadKeyboardData(newDevice);
    } else {
      // 设置设备连接状态
      setDeviceStatus(true);
      setDeviceOnline(true);
      // 加载键盘数据
      await loadKeyboardData(newDevice);
    }
    newDevice.onListeners.push({
      name: "battery",
      fb: (value: any) => {
        setBattery(value.battery);
        setChargeFlag(value.charge_flag);
      },
    });

    newDevice.onListeners.push({
      name: "match",
      fb: (value: any) => {
        //console.log(value);
      },
    });
    return true;
  };

  // 设备断开
  const disconnectKeyboard = () => {
    // 设置设备连接状态
    setDeviceStatus(false);
    setDeviceOnline(false);
    setConnectedKeyboard(undefined);
  };

  // 修改loadKeyboardData函数
  const loadKeyboardData = async (connectedKeyboard: DeviceComm) => {
    try {
      // 初始化宏配置
      const macro_data = localStorage.getItem(localMacroName);
      let macroProfiles_: MacroProfile[];

      if (macro_data) {
        macroProfiles_ = JSON.parse(macro_data);
        console.log("macroProfiles_", macroProfiles_);
        setMacroProfiles(macroProfiles_);
      }

      // 继续加载其他键盘数据
      const curProfileIndex = parseInt(
        localStorage.getItem(localProfileName + "select") || "0"
      );
      if (curProfileIndex) {
        setProfileIndex(curProfileIndex);
      }

      // 先加载配置文件数据
      let profiles_: KeyboardProfile[];
      const profiles_data = localStorage.getItem(localProfileName);
      if (profiles_data) {
        profiles_ = JSON.parse(profiles_data);
        setProfiles(profiles_);
        // 设置键盘按键数据
        if (profiles_[curProfileIndex] && profiles_[curProfileIndex].kbKeys) {
          // 直接使用数据而不是等待setState
          setKeyInfos(profiles_[curProfileIndex].kbKeys);
          setKeyColor(profiles_[curProfileIndex].keyColor);
        } else {
          // 如果没有配置文件数据，使用默认配置
          await loadKeyboardDefaultConfig();
        }
      } else {
        // 如果没有配置文件，使用默认配置
        await loadKeyboardDefaultConfig();
      }
      // 获取灯光模式
      const lightMode = await connectedKeyboard.getLightInfo();
      console.log("lightMode", lightMode);
      setCurrentLightMode(lightMode.mode);
      setLockWin(lightMode.lockWin);
      setLockAltF4(lightMode.lockAltF4);
      setLockAltTab(lightMode.lockAltTab);
      setBattery(100);
      // const battery_info = await connectedKeyboard.getBatteryInfo();
      // console.log("battery_info", battery_info);
      // setBattery(battery_info.battery_value);
      // setChargeFlag(battery_info.charge_flag);
    } catch (error) {
      console.error("加载键盘数据失败:", error);
      await loadKeyboardDefaultConfig();
    }
  };

  // 初始化键盘配置方案
  const initKeyboardProfiles = (keyboardProfiles: KeyboardProfile[]) => {
    const res = localStorage.getItem(localProfileName);
    if (res) {
      try {
        const profiles = JSON.parse(res);
        setProfiles(profiles);
      } catch (error) {
        console.error("加载本地配置失败:", error);
      }
    } else {
      setProfiles(keyboardProfiles);
      localStorage.setItem(localProfileName, JSON.stringify(keyboardProfiles));
    }
  };

  const activeProfile = async (profileIndex: number) => {
    const newProfiles = profiles.map((profile, index) =>
      index == profileIndex
        ? { ...profile, active: true }
        : { ...profile, active: false }
    );
    setProfiles(_.cloneDeep(newProfiles));
    localStorage.setItem(localProfileName, JSON.stringify(newProfiles));
    setKeyInfos(newProfiles[profileIndex].kbKeys);
    setKeyColor(newProfiles[profileIndex].keyColor);
    if (connectedKeyboard) {
      await connectedKeyboard.setLightInfo(
        newProfiles[profileIndex].lightInfo[0]
      );
      await connectedKeyboard.setAllKeyInfo(newProfiles[profileIndex].kbKeys);
    }
  };

  // 更新键盘按键信息
  const updateKeyboardKeys = (kbKeys: KeyInfo[]) => {
    console.log("updateKeyboardKeys", kbKeys);
    console.log("profileIndex", profileIndex);
    const newProfiles = profiles.map((profile, index) =>
      index == profileIndex ? { ...profile, kbKeys: kbKeys } : profile
    );
    setProfiles(_.cloneDeep(newProfiles));
    localStorage.setItem(localProfileName, JSON.stringify(newProfiles));
    console.log("updateKeyboardKeys, newProfiles", newProfiles);
  };

  // 更新键盘按键颜色
  const updateKeyboardKeyColor = (keyColor: KeyColor[]) => {
    const newProfiles = profiles.map((profile, index) =>
      index == profileIndex ? { ...profile, keyColor: keyColor } : profile
    );
    setProfiles(_.cloneDeep(newProfiles));
    localStorage.setItem(localProfileName, JSON.stringify(newProfiles));
    console.log("updateKeyboardKeyColor, newProfiles", newProfiles);
  };

  // 恢复键盘出厂设置
  const restoreKeyboardFactorySettings = async (
    connectedKeyboard: DeviceComm
  ) => {
    try {
      console.log("[restoreKeyboardFactorySettings] 开始恢复出厂设置");

      // 获取默认配置
      let defaultConfig: any = await import("@/src/data/layout/k81.json");

      // 遍历键盘按键布局，生成按键信息
      const standardLayerKeys = defaultConfig.default.layouts.keys.map(
        (key: KeyItem) => {
          return {
            index: key.index,
            layer: 0,
            keyValue: key.code,
            keyName: key.name,
            lang: "",
            type: 0x00,
            code1: 0x00,
            code2: 0x00,
            code3: 0x00,
            fnName1: "",
            fnType: 0x00,
            fnCode1: 0x00,
            fnCode2: 0x00,
            fnCode3: 0x00,
          };
        }
      );
      const keyColor: KeyColor[] = defaultConfig.default.layouts.keys.map(
        (key: KeyItem) => {
          return {
            index: key.index,
            keyValue: key.code,
            keyName: key.name,
            keyColor: "#000000",
          };
        }
      );
      setKeyColor(keyColor);

      // 创建新的配置文件数组，确保深拷贝
      const newProfiles = profiles.map((profile, index) => ({
        ...profile,
        active: index === profileIndex,
        kbKeys: _.cloneDeep(standardLayerKeys),
        keyColor: _.cloneDeep(keyColor),
      }));

      // 更新状态和存储
      setProfiles(newProfiles);
      localStorage.setItem(localProfileName, JSON.stringify(newProfiles));

      // 更新当前显示的按键信息
      const currentProfileKeys = _.cloneDeep(newProfiles[profileIndex].kbKeys);
      setKeyInfos(currentProfileKeys);

      // 更新灯光信息
      const lightInfo = _.cloneDeep(newProfiles[profileIndex].lightInfo);
      setLightInfo(lightInfo);
      setCurrentLightMode(0x00);

      // 重置锁定状态
      setLockWin(0);
      setLockAltF4(0);
      setLockAltTab(0);

      // 清空宏配置
      localStorage.removeItem(localMacroName);
      setMacroProfiles([]);

      // 更新键盘配置
      // 更新设备按键
      if (connectedKeyboard) {
        // 恢复出厂设置
        await connectedKeyboard.restoreKeyboardFactorySettings();
      }

      console.log("[restoreKeyboardFactorySettings] 恢复出厂设置成功");
      return true;
    } catch (error) {
      console.error(
        "[restoreKeyboardFactorySettings] 恢复出厂设置失败:",
        error
      );
      return false;
    }
  };

  const mainProps: MainProps = {
    softwareVersion,
    connectedKeyboard,
    connectKeyboard,
    disconnectKeyboard,

    demoMode,
    setDemoMode,

    connectMode,
    deviceStatus,
    setDeviceStatus,
    deviceOnline,
    setDeviceOnline,
    deviceName,
    setDeviceName,
    deviceId,
    setDeviceId,
    deviceVersion,
    setDeviceVersion,
    dongleVersion,
    setDongleVersion,
    currentTab,
    setCurrentTab,
    isRecordingMacro,
    setIsRecordingMacro,

    profileIndex,
    setProfileIndex,
    activeProfile,
    profiles,
    setProfiles,
    updateKeyboardKeys,
    updateKeyboardKeyColor,

    fnLayer,
    setFnLayer,
    selectedKeyIndex,
    setSelectedKeyIndex,
    multiSelectKeys,
    setMultiSelectKeys,

    keyInfos,
    setKeyInfos,
    kbMatrix,
    setKbMatrix,
    keyColor,
    setKeyColor,
    currentLightMode,
    setCurrentLightMode,
    currentColor,
    setCurrentColor,
    lockWin,
    setLockWin,
    lockAltF4,
    setLockAltF4,
    lockAltTab,
    setLockAltTab,

    localMacroName,
    macroProfiles,
    setMacroProfiles,
    selectMacroProfile,
    setSelectMacroProfile,

    battery,
    chargeFlag,
    t,
    editMode: "",
    setEditMode: () => {},
    setMacroData: () => {},

    lightInfo,
    setLightInfo,
    restoreKeyboardFactorySettings,
  };

  return (
    <MainContext.Provider value={mainProps}>{children}</MainContext.Provider>
  );
}

export default MainProvider;
